package com.leyou.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
public class UploadService {
    private final static List<String> CONTENT_TYPES=Arrays.asList("image/gif","image/jpeg");
    private final static Logger LOGGER= LoggerFactory.getLogger(UploadService.class);
    @Autowired
    private FastFileStorageClient storageClient;
    /**
     * 文件上传
     * @param file
     * @return
     */
    public String uploadImage(MultipartFile file) {
        //获取文件名
        String originalFilename=file.getOriginalFilename();
        try {
            //1.校验文件类型
            //获取文件类型
            String contentType = file.getContentType();
            if(!CONTENT_TYPES.contains(contentType)){
                //如果不存在则返回null
                LOGGER.info("文件类型不合法：{}",originalFilename);
                return null;
            }
            //2.校验文件内容
            //利用ImageIO工具类来校验文件是否是图片，返回Null则不是图片
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if(bufferedImage==null){
                LOGGER.info("文件内容不合法：{}",originalFilename);
                return null;
            }
            //3.校验通过保存到服务器
            //file.transferTo(new File("F:\\Java\\Java_project\\idea_demo\\leyou\\image\\"+originalFilename));
            //使用FastDFS上传图片
            //获取扩展名
            String ext = StringUtils.substringAfterLast(originalFilename, ".");
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);
            //返回url,回显图片路径，这里使用nginx代理图片路径
            //return "http://image.leyou.com/"+originalFilename;
            return "http://image.leyou.com/"+storePath.getFullPath();
        } catch (IOException e) {
            LOGGER.info("服务器内部错误：{}",originalFilename);
            e.printStackTrace();
        }
        return null;

    }
}
